<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="「好文翻译」为什么你可以删除 90% 的 useMemo 和 useCallback ？, 夯鸟">
    <meta name="description" content="疑难杂症">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>「好文翻译」为什么你可以删除 90% 的 useMemo 和 useCallback ？ | 夯鸟</title>
    <link rel="icon" type="image/png" href="/ycs/favicon.png">
    


    <!-- bg-cover style     -->



<link rel="stylesheet" type="text/css" href="/ycs/libs/awesome/css/all.min.css">
<link rel="stylesheet" type="text/css" href="/ycs/libs/materialize/materialize.min.css">
<link rel="stylesheet" type="text/css" href="/ycs/libs/aos/aos.css">
<link rel="stylesheet" type="text/css" href="/ycs/libs/animate/animate.min.css">
<link rel="stylesheet" type="text/css" href="/ycs/libs/lightGallery/css/lightgallery.min.css">
<link rel="stylesheet" type="text/css" href="/ycs/css/matery.css">
<link rel="stylesheet" type="text/css" href="/ycs/css/my.css">
<link rel="stylesheet" type="text/css" href="/ycs/css/dark.css" media="none" onload="if(media!='all')media='all'">




    <link rel="stylesheet" href="/ycs/libs/tocbot/tocbot.css">
    <link rel="stylesheet" href="/ycs/css/post.css">




    
        <link rel="stylesheet" type="text/css" href="/ycs/css/reward.css">
    



    <script src="/ycs/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 6.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/ycs/atom.xml" title="夯鸟" type="application/atom+xml">
</head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/ycs/" class="waves-effect waves-light">
                    
                    <img src="/ycs/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">夯鸟</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ycs/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ycs/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ycs/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ycs/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ycs/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ycs/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>联系</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ycs/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情推荐</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  <li>
    <a href="javascript:;" class="waves-effect waves-light" onclick="switchNightMode()" title="深色/浅色模式" >
      <i id="sum-moon-icon" class="fas fa-sun" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/ycs/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">夯鸟</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/ycs/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ycs/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ycs/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ycs/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ycs/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ycs/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			联系
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ycs/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情推荐
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/chunsuo/blog" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/chunsuo/blog" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://cn.bing.com/th?id=OHR.MidAutumn2022_ZH-CN9825550508_1920x1200.jpg&rf=LaDigue_1920x1200.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">「好文翻译」为什么你可以删除 90% 的 useMemo 和 useCallback ？</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/ycs/tags/javascript/">
                                <span class="chip bg-color">javascript</span>
                            </a>
                        
                            <a href="/ycs/tags/React/">
                                <span class="chip bg-color">React</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/ycs/categories/React/" class="post-category">
                                React
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2023-07-18
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-07-19
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    5.1k
                </div>
                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/ycs/libs/prism/prism.min.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="译者前言"><a href="#译者前言" class="headerlink" title="译者前言"></a>译者前言</h2><p>之前发了一条掘金沸点：</p>
<p><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/02a12444e43949f38fe9d3587801e52d~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<p>下面有同学吐槽纯英文，我遂有了翻译的想法。翻译已得到原作者允许，原文地址见下。作者博客中还有许多好文章，英文还行的读者可以去看看，可以说是我全网所见的关于 React 性能优化方面最好的文章（评论区也极有营养，不要错过）。如果英文不好，也没关系，如果本文受欢迎，我后面也会考虑继续翻译下去。</p>
<p><a href="https://link.juejin.cn/?target=https://www.developerway.com/posts/how-to-use-memo-use-callback">www.developerway.com/posts/how-t…</a></p>
<p>作者是：Nadia Makarevich</p>
<h2 id="不多废话，正文开始"><a href="#不多废话，正文开始" class="headerlink" title="不多废话，正文开始"></a>不多废话，正文开始</h2><p>如果你不是一个 React 纯新手，那么你大概对 <code>useMemo</code> 和 <code>useCallback</code> 已经比较熟悉了。如果你在负责开发或维护一个中等规模或大规模的应用，你有可能将你的应用程序的某些部分吐槽为 “难以理解的 <code>useMemo</code> 和 <code>useCallbacks</code> 链条，无法阅读和调试”。</p>
<p>这些 hooks 似乎有一种不受控制自行扩散的魔力，直到它们完全控制你的仓库。你会发现，你自己，以及你身边的同事，都正在四面八方孜孜不倦地写下它们。</p>
<p>你知道令人悲伤的一点是什么吗？这些都是<strong>完完全全的无用功</strong>。你当下就可以删除你代码中至少 90% 的 <code>useMemo</code> 和 <code>useCallback</code> ，与此同时你的应用跑起来完全 OK，甚至还比原来快了那么一丢丢。不要误会我的意思，我不是说 <code>useMemo</code> 和 <code>useCallback</code> 完全没用。只是他们的用途只被限制在少数非常特殊并且确定的场景下。除此之外，大部分时间里我们都在毫无意义地把业务代码包裹在它们里面。</p>
<p>这就是我今天要说的：开发者会犯哪些和 <code>useMemo</code> 与 <code>useCallback</code> 有关的错误？这两个 hooks 的真实目的是什么，并且我们该如何恰当地使用它们。</p>
<p>有两个主要原因导致了这两个 hooks 恶心地向四面八方扩散：</p>
<ul>
<li>缓存（memorize） props，从而防止组件重渲染(re-render)</li>
<li>缓存某些值，从而避免在每次重渲染时执行开销昂贵的计算任务</li>
</ul>
<p>我们将在下面的文章里仔细审视这两个原因，但第一点是：<code>useMemo</code> 和 <code>useCallback</code> 的目的到底是什么？</p>
<h2 id="我们为什么需要-useMemo-和-useCallback-？"><a href="#我们为什么需要-useMemo-和-useCallback-？" class="headerlink" title="我们为什么需要 useMemo 和 useCallback ？"></a>我们为什么需要 useMemo 和 useCallback ？</h2><p>答案很简单：在每次<strong>重渲染之间</strong>缓存数据。如果一个值或函数被包裹在这两个 hooks 中，react 就会在首次渲染时缓存这个值或函数。在接下来的每次重渲染时，都会返回这个缓存的值。如果不使用它们，所有非原始类型的值，如 <code>array</code>、<code>object</code>，或 <code>function</code>，都会在每一次重渲染时被彻底重新创建。</p>
<p>如果你需要在每次重渲染时比较这些值，那么缓存它们是很有用的。这其实和普通的 javascript 没什么区别：</p>
<pre class="line-numbers language-vbscript" data-language="vbscript"><code class="language-vbscript">vbscript复制代码const a = { "test": 1 };
const b = { "test": 1'};
console.log(a === b); // 值为 false
const c = a; // "c" 仅仅是 "a" 的引用
console.log(a === c); // 值为 true<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>或者，更接近于我们的典型 React 应用的话，例子是这样的：</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const Component</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>  
  <span class="token key attr-name">const a</span> <span class="token punctuation">=</span> <span class="token value attr-value">{ test: 1 };</span>
  <span class="token key attr-name">useEffect(()</span> <span class="token punctuation">=</span><span class="token value attr-value">&gt; {</span>    
    // "a" 将会在每次重渲染时被比较
  }, [a]);
  // 你剩下的代码
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>a</code> 是 <code>useEffect</code> hook 的依赖项。在 <code>Component</code> 的每次重渲染时， <code>React</code> 都会把它与的值与上次渲染时的值做比较. <code>a</code> 是一个在 <code>Component</code> 内部定义的 <code>object</code>，这意味着在每次重渲染时，<code>a</code> 都会被完完全全地重新创建(re-create)。因此，比较”重渲染之前的 <code>a</code>“ 和 ”重渲染之后的 <code>a</code>“，结果都会是 <code>false</code>，所以被 <code>useEffect</code> 包裹的函数也将会在每次重渲染的过程中触发调用。</p>
<p>为了避免以上结果，我们可以把 <code>a</code> 包裹在 <code>useMemo</code> 中：</p>
<pre class="line-numbers language-scss" data-language="scss"><code class="language-scss">scss复制代码const Component = <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token selector">=&gt; </span><span class="token punctuation">{</span>
  <span class="token comment">// 在每次重渲染之间保存 a</span>
  const a = <span class="token function">useMemo</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> =&gt; <span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token property">test</span><span class="token punctuation">:</span> 1 <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">,</span> []<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">useEffect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token selector">=&gt; </span><span class="token punctuation">{</span>
    <span class="token comment">// 只有当 a 的值真实发生改变时才会触发</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span> [a]<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 你剩下的代码</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>现在 <code>useEffect</code> 中的方法只有在 <code>a</code> 值确实发生变化的时候才会触发（不过在本例中这不会发生）。</p>
<p><code>useCallback</code> 也是同样的道理，只不过它对于缓存函数更有用：</p>
<pre class="line-numbers language-scss" data-language="scss"><code class="language-scss">scss复制代码const Component = <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token selector">=&gt; </span><span class="token punctuation">{</span>
  <span class="token comment">// 在每次重渲染之间保存 onClick 方法</span>
  const fetch = <span class="token function">useCallback</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token selector">=&gt; </span><span class="token punctuation">{</span>
    console.<span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'fetch some data here'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
  <span class="token punctuation">}</span><span class="token punctuation">,</span> []<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token function">useEffect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token selector">=&gt; </span><span class="token punctuation">{</span>    
    <span class="token comment">// 只有当 fetch 的值真的发生该表的时候才会触发</span>
    <span class="token function">fetch</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
  <span class="token punctuation">}</span><span class="token punctuation">,</span> [fetch]<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 你剩下的代码</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>在这里，需要记住的最重要的一件事是，<code>useMemo</code> 和 <code>useCallback</code> 只有在<strong>重渲染的过程中</strong>才有用。在初始渲染过程中，它们不仅是无用的，甚至是有害的：它们会让 React 做很多额外的工作。这意味着你的应用在初始渲染过程中会<strong>稍稍更慢</strong>一些。并且，如果你的应用有数百个这些 hooks 分布在各处，那么这些轻微的影响初始渲染的作用就可以被观察到。</p>
<h2 id="缓存-props-以避免重渲染"><a href="#缓存-props-以避免重渲染" class="headerlink" title="缓存 props 以避免重渲染"></a>缓存 props 以避免重渲染</h2><p>既然我们已经知道了这俩 hooks 的作用，让我们考察一下它们。其中最重要的一点，也是最常被用到的一点，就是缓存 props 以避免重渲染。如果你的应用中也存在类似下面的代码片段，请给我吹个口哨：</p>
<ol>
<li><p>把 onClick 包裹在 useCallback 中以避免重渲染</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const Component</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>
  <span class="token key attr-name">const onClick</span> <span class="token punctuation">=</span> <span class="token value attr-value">useCallback(</span>
    <span class="token key attr-name">()</span> <span class="token punctuation">=</span><span class="token value attr-value">&gt; {    /* do something */  }, []</span>
  );
  return (
    &lt;&gt;
      <span class="token key attr-name">&lt;button onClick</span><span class="token punctuation">=</span><span class="token value attr-value">{onClick}&gt;Click me&lt;/button&gt;</span>
     ... // 其他组件  
    &lt;/&gt;  
  );
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>把 onClick 包裹在 useCallback 中以避免重渲染</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const Item</span> <span class="token punctuation">=</span> <span class="token value attr-value">({ item, onClick, value }) =&gt; &lt;button onClick={onClick}&gt;</span>
  {item.name}&lt;/button&gt;;
<span class="token key attr-name">const Component</span> <span class="token punctuation">=</span> <span class="token value attr-value">({ data }) =&gt; {</span>
  <span class="token key attr-name">const value</span> <span class="token punctuation">=</span> <span class="token value attr-value">{ a: someStateValue };</span>
  <span class="token key attr-name">const onClick</span> <span class="token punctuation">=</span> <span class="token value attr-value">useCallback(() =&gt; {    /* do something on click */  }, []);</span>
  return (
    &lt;&gt;
      <span class="token key attr-name">{data.map((d)</span> <span class="token punctuation">=</span><span class="token value attr-value">&gt; (</span>
        <span class="token key attr-name">&lt;Item item</span><span class="token punctuation">=</span><span class="token value attr-value">{d} onClick={onClick} value={value} /&gt;</span>
      ))}
    &lt;/&gt;
  );
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>把 value 包裹在 useMemo 中，因为它是被缓存的 onClick 的依赖：</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const Item</span> <span class="token punctuation">=</span> <span class="token value attr-value">({ item, onClick }) =&gt; &lt;button onClick={onClick}&gt;</span>
  {item.name}
&lt;/button&gt;;
<span class="token key attr-name">const Component</span> <span class="token punctuation">=</span> <span class="token value attr-value">({ data }) =&gt; {</span>
  <span class="token key attr-name">const value</span> <span class="token punctuation">=</span> <span class="token value attr-value">useMemo(() =&gt; ({ a: someStateValue }), [someStateValue]);</span>
  <span class="token key attr-name">const onClick</span> <span class="token punctuation">=</span> <span class="token value attr-value">useCallback(() =&gt; {    console.log(value);  }, [value]);</span>
  return (
    &lt;&gt;
      <span class="token key attr-name">{data.map((d)</span> <span class="token punctuation">=</span><span class="token value attr-value">&gt; (&lt;Item item={d} onClick={onClick} /&gt;))}</span>
    &lt;/&gt;
  );
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
</ol>
<p>以上是否就是你曾经干过的，或者见别人干过的事儿？你是否同意 hook 解决了你想让它们解决的问题？如果你的答案是 yes，那么恭喜了，<code>useMemo</code> 和 <code>useCallback</code> 劫持了你，并且毫无必要地控制了你的生活。在以上所有的例子里，这两个 hooks 都<strong>毫无作用。</strong>它们让代码变得复杂，拖慢了初始渲染，却没有阻止任何事情（指重渲染）。</p>
<p>如果想要知道为什么，我们需要记住一件有关 React 如何工作的最重要的事：为什么一个组件会重渲染它自己。</p>
<h2 id="为什么一个组件会重渲染它自己？"><a href="#为什么一个组件会重渲染它自己？" class="headerlink" title="为什么一个组件会重渲染它自己？"></a>为什么一个组件会重渲染它自己？</h2><p>“当 state 或者 prop 发生变化的时候，组件就会重渲染自己”，这是一个有关 React 的共识。甚至 <a href="https://link.juejin.cn/?target=https://legacy.reactjs.org/docs/react-component.html%23updating">React 官方文档</a>也提到了这一点。我认为这一申明得出了一个错误的推论：“如果 prop 没有变化（比如，被缓存了），那组件就不会重渲染。”（译者注：以上推论是一个典型的逻辑错误，A 是 B 的充分条件，并不意味着 !A 是 !B 的充分条件。）</p>
<p>上面这句话之所以是错误的，就是因为还有一个重要的原因会导致组件重渲染：<strong>当组件的父组件重渲染！</strong></p>
<p>或者说，如果我们从相反的角度考虑：当一个组件重渲染它自己的时候，它也会同时重渲染它的 children。看一下下面的代码示例：</p>
<pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript">javascript复制代码<span class="token keyword">const</span> <span class="token function-variable function">App</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> <span class="token punctuation">[</span>state<span class="token punctuation">,</span> setState<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">useState</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> <span class="token punctuation">(</span>
    <span class="token operator">&lt;</span>div className<span class="token operator">=</span><span class="token string">"App"</span><span class="token operator">&gt;</span>
      <span class="token operator">&lt;</span>button onClick<span class="token operator">=</span><span class="token punctuation">{</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token function">setState</span><span class="token punctuation">(</span>state <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">}</span><span class="token operator">&gt;</span>
        click to re<span class="token operator">-</span>render <span class="token punctuation">{</span>state<span class="token punctuation">}</span>
      <span class="token operator">&lt;</span><span class="token operator">/</span>button<span class="token operator">&gt;</span>
      <span class="token operator">&lt;</span>br <span class="token operator">/</span><span class="token operator">&gt;</span>
      <span class="token operator">&lt;</span>Page <span class="token operator">/</span><span class="token operator">&gt;</span>
    <span class="token operator">&lt;</span><span class="token operator">/</span>div<span class="token operator">&gt;</span>
  <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>App</code> 组件有一些 state，也有一些 children，包括 <code>Page</code> 组件。打不过 button 被点击的时候，会发生什么呢？State 会变化，它会导致 App 的重渲染，并且会触发它重渲染它所有的 children，包括 <code>Page</code> 组件。在这过程中 <code>Page</code> 组件甚至没有 props！</p>
<p>现在，在 <code>Page</code> 组件中，如果我们存在一个这样的 children：</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini">ini
<span class="token key attr-name">复制代码const Page</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; &lt;Item /&gt;;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>它完全是空的，既没有 state，也没有 props。但是当 App 重渲染的时候， Page 组件依旧会重渲染，并连同重渲染它内部的 Item 组件。App 组件的 state 变化触发了应用内的一整个重渲染链条。可以在这个 codesandbox 中看到<a href="https://link.juejin.cn/?target=https://codesandbox.io/s/parent-children-re-renders-gihtcw?file=/src/App.tsx">完整示例</a>。</p>
<p>唯一去打断这链条的办法，是去缓存组件内的子组件。我们能够用 <code>useMemo</code> 做到这些，更好的方法则是使用 <a href="https://link.juejin.cn/?target=https://legacy.reactjs.org/docs/react-api.html%23reactmemo">React.memo</a> 工具函数。只有当组件被包裹在其以内时，React 才会在重渲染之前先停下来检查一下 props 是否产生了变化。</p>
<p>这样缓存一个组件：</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const Page</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; &lt;Item /&gt;;</span>
<span class="token key attr-name">const PageMemoized</span> <span class="token punctuation">=</span> <span class="token value attr-value">React.memo(Page);</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>在一个包含 state 的 App 中使用它：</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const App</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>
  <span class="token key attr-name">const [state, setState]</span> <span class="token punctuation">=</span> <span class="token value attr-value">useState(1);</span>
  return (
    ... // same code as before
    &lt;PageMemoized /&gt;
  );
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>在以上，并且<strong>只有</strong>在以上场景中，props 是否被缓存才是重要的。</p>
<p>让我们想象 <code>Page</code> 组件存在一个 <code>onClick</code> prop，它接收一个函数。如果我在不缓存这个函数的情况下，把它传递给 <code>Page</code>，会发生什么呢？</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const App</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>
  <span class="token key attr-name">const [state, setState]</span> <span class="token punctuation">=</span> <span class="token value attr-value">useState(1);</span>
  <span class="token key attr-name">const onClick</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>
    console.log('Do something on click');
  };
  return (
    // 不管 onClick 有没有缓存，page 都会重渲染
    <span class="token key attr-name">&lt;Page onClick</span><span class="token punctuation">=</span><span class="token value attr-value">{onClick} /&gt;</span>
  );
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>App</code> 会重渲染，React 会在 App 的 children 中找到 <code>Page</code> 组件，并且重渲染它。<code>onClick</code> 是否包裹在 <code>useCallback</code> 中并不重要。</p>
<p>那么如果我们把 <code>Page</code> 组件缓存起来了呢？</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const PageMemoized</span> <span class="token punctuation">=</span> <span class="token value attr-value">React.memo(Page);</span>
<span class="token key attr-name">const App</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>
  <span class="token key attr-name">const [state, setState]</span> <span class="token punctuation">=</span> <span class="token value attr-value">useState(1);</span>
  <span class="token key attr-name">const onClick</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>
    console.log('Do something on click');
  };
  return (
    // 因为 onClick 没有缓存，PageMemoized 「将会」重渲染
    <span class="token key attr-name">&lt;PageMemoized onClick</span><span class="token punctuation">=</span><span class="token value attr-value">{onClick} /&gt;</span>
  );
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>App</code> 会重渲染，React 会在它的 children 中发现 <code>PageMemoized</code> 组件，并意识到它被 <code>React.memo</code> 方法包裹，这会打断重渲染链条，React 会事先检查这个组件的 props 是否有变化。在这个例子里，既然 <code>onClick</code> 是一个未被缓存的函数，props 比较的结果就会是 <code>false</code>，那么 <code>PageMemoized</code> 组件就会重渲染它自己。</p>
<p>最后，让我们来看看 useCallback 的应用：</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const PageMemoized</span> <span class="token punctuation">=</span> <span class="token value attr-value">React.memo(Page);</span>
<span class="token key attr-name">const App</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>
  <span class="token key attr-name">const [state, setState]</span> <span class="token punctuation">=</span> <span class="token value attr-value">useState(1);</span>
  <span class="token key attr-name">const onClick</span> <span class="token punctuation">=</span> <span class="token value attr-value">useCallback(</span>
    <span class="token key attr-name">()</span> <span class="token punctuation">=</span><span class="token value attr-value">&gt; { console.log('Do something on click');  },</span> 
    <span class="token section"><span class="token punctuation">[</span><span class="token punctuation">]</span></span>
  );
  return (
    // PageMemoized 因为 onClick 被缓存了，将「不会」重渲染
    <span class="token key attr-name">&lt;PageMemoized onClick</span><span class="token punctuation">=</span><span class="token value attr-value">{onClick} /&gt;</span>
  );
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>现在，当 React 检查 <code>PageMemoized</code> 的 props 有无变化时，<code>onClick</code> 将会保持不变，只有在这种情况下， <code>PageMemoized</code> 才不会重渲染。</p>
<p>如果我给 PageMemoized 组件增加另一个非缓存的值，将会发生什么呢？就像下面的场景：</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const PageMemoized</span> <span class="token punctuation">=</span> <span class="token value attr-value">React.memo(Page);</span>
<span class="token key attr-name">const App</span> <span class="token punctuation">=</span> <span class="token value attr-value">() =&gt; {</span>
  <span class="token key attr-name">const [state, setState]</span> <span class="token punctuation">=</span> <span class="token value attr-value">useState(1);</span>
  <span class="token key attr-name">const onClick</span> <span class="token punctuation">=</span> <span class="token value attr-value">useCallback(</span>
    <span class="token key attr-name">()</span> <span class="token punctuation">=</span><span class="token value attr-value">&gt; { console.log('Do something on click'); },</span>
    <span class="token section"><span class="token punctuation">[</span><span class="token punctuation">]</span></span>
  );
  return (
    // 因为 value 没有被缓存，page 「将会」重渲染
    <span class="token key attr-name">&lt;PageMemoized onClick</span><span class="token punctuation">=</span><span class="token value attr-value">{onClick} value={[1, 2, 3]} /&gt;</span>
  );
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>React 停下来检查 <code>PageMemoized</code> 组件的 props 是否发生变化，<code>onClick</code> 确实没变化，但是 <code>value</code> 变化了，那么 <code>PageMemoized</code> 还是会重渲染！可以在<a href="https://link.juejin.cn/?target=https://codesandbox.io/s/everything-memoized-8oltqg?file=/src/App.tsx">这里</a>看完整示例，试一下删除缓存，看看组件里的每样东西是如何重渲染的。</p>
<p>思考一下以上示例，我们可以得出结论，只有在唯一的一种场景下，缓存 props 才是有意义的：<strong>当组件的每一个 prop，以及组件本身被缓存的时候</strong>。</p>
<p>如果组件代码里有以下情形，我们可以毫无心理负担地删掉 <code>useMemo</code> 和 <code>useCallback</code>：</p>
<ul>
<li>它们被作为 attributes ，直接地或作为依赖树的上层，被传递到某个 DOM 上</li>
<li>它们被作为 props，直接地或作为依赖树的上层，被传递到某个未被缓存的组件上</li>
<li>它们被作为 props，直接地或作为依赖树的上层，被传递到某个组件上，而那个组件至少有一个 prop 未被缓存</li>
</ul>
<p><strong>但为啥不修复缓存（指给组件、及组件所有的 prop 加上缓存），而是要删掉它们呢？</strong>那是因为：如果你因为组件的重渲染而出现了某些性能问题，你肯定已经注意到，并且修复掉它们了，对吧？（译者注：即给所有的 prop 和组件本身加上了缓存，不是以上列出的三情况之一了）。 😉剩下的既然没有性能问题，就也没必要去 fix 代码啦（直接删了更好）。删除无用的 <code>useMemo</code> 和 <code>useCallback</code> 将会简化你的代码，并且在初次渲染时稍稍提速，同时不会对现有的重渲染性能产生任何负面影响。</p>
<h2 id="在每次重渲染时避免开销巨大的运算"><a href="#在每次重渲染时避免开销巨大的运算" class="headerlink" title="在每次重渲染时避免开销巨大的运算"></a>在每次重渲染时避免开销巨大的运算</h2><p>就像上文以及 <a href="https://link.juejin.cn/?target=https://legacy.reactjs.org/docs/hooks-reference.html%23usememo">React 官方文档</a>提到的，<code>useMemo</code> 最主要的作用，就是在每次的渲染过程中避免开销巨大的运算。在叙述中，并没有提到什么算是“开销巨大”的运算。结果就是，开发者往往在 render 方法中滥用 <code>useMemo</code>。创建一个新日期对象？filer、或 map 、或 sort 一个数组？创建一个普通 object 对象？都用 <code>useMemo</code> 包裹一下吧！</p>
<p>好吧，让我们看一组数字。考虑我们有一个国家列表（大概有 250 个元素），并且我们希望在页面上展示它们，并且允许用户去执行排序操作。</p>
<pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript">javascript复制代码<span class="token keyword">const</span> <span class="token function-variable function">List</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token parameter"><span class="token punctuation">{</span> countries <span class="token punctuation">}</span></span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// sorting list of countries here</span>
  <span class="token keyword">const</span> sortedCountries <span class="token operator">=</span> <span class="token function">orderBy</span><span class="token punctuation">(</span>countries<span class="token punctuation">,</span> <span class="token string">'name'</span><span class="token punctuation">,</span> sort<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> <span class="token punctuation">(</span>
    <span class="token operator">&lt;</span><span class="token operator">&gt;</span>
      <span class="token punctuation">{</span>
        sortedCountries<span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">country</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">(</span>
          <span class="token operator">&lt;</span>Item country<span class="token operator">=</span><span class="token punctuation">{</span>country<span class="token punctuation">}</span> key<span class="token operator">=</span><span class="token punctuation">{</span>country<span class="token punctuation">.</span>id<span class="token punctuation">}</span> <span class="token operator">/</span><span class="token operator">&gt;</span>
        <span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
    <span class="token operator">&lt;</span><span class="token operator">/</span><span class="token operator">&gt;</span>
  <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>问题是：给 250 个元素排序属于开销巨大的操作么？感觉好像是，但到底是不是呢？我们可以将它用 <code>useMemo</code> 包裹以避免在重渲染中重新计算一遍，是吗？其实，这个问题的答案是很容易度量的，使用我们常用的 performance api 就行了。</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const List</span> <span class="token punctuation">=</span> <span class="token value attr-value">({ countries }) =&gt; {</span>
  <span class="token key attr-name">const before</span> <span class="token punctuation">=</span> <span class="token value attr-value">performance.now();</span>
  <span class="token key attr-name">const sortedCountries</span> <span class="token punctuation">=</span> <span class="token value attr-value">orderBy(countries, 'name', sort);</span>
  // this is the number we're after
  <span class="token key attr-name">const after</span> <span class="token punctuation">=</span> <span class="token value attr-value">performance.now() - before;</span>
  return (    // same  )
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>最终结果如何呢？如果不缓存的话，在设置 6倍 CPU 减速的情况下（译者注：Chrome 开发者工具有这个功能，允许开发者模拟在低性能 PC 上的访问体验），给 250 个元素排序耗时<strong>少于 2 毫秒。</strong>作为比较，渲染这个列表——仅仅是原生的按钮上带文字——就消耗了 20 毫秒。多十倍啊！请看<a href="https://link.juejin.cn/?target=https://codesandbox.io/s/measure-without-memo-tnhggk?file=/src/page.tsx">完整示例</a>。</p>
<p>在实际场景中，数组往往比示例中的更小，同时渲染的内容比示例中的更复杂，因此更慢。所以总的来说「计算」与「渲染」之间的耗时往往超过 10 倍。</p>
<p>与其说缓存数组操作，我们更应该缓存的是实际上是最耗时的计算——重渲染并更新组件。像下面这样：</p>
<pre class="line-numbers language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">ini复制代码const List</span> <span class="token punctuation">=</span> <span class="token value attr-value">({ countries }) =&gt; {</span>
  <span class="token key attr-name">const content</span> <span class="token punctuation">=</span> <span class="token value attr-value">useMemo(() =&gt; {</span>
    <span class="token key attr-name">const sortedCountries</span> <span class="token punctuation">=</span> <span class="token value attr-value">orderBy(countries, 'name', sort);</span>
    <span class="token key attr-name">return sortedCountries.map((country)</span> <span class="token punctuation">=</span><span class="token value attr-value">&gt;</span>
      <span class="token key attr-name">&lt;Item country</span><span class="token punctuation">=</span><span class="token value attr-value">{country} key={country.id} /&gt;</span>
    );
  }, [countries, sort]);
  return content;
};<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>以上 <code>useMemo</code> 把大约 20ms 的重渲染时间，减少了不到 2ms（也就是 18ms 左右）。</p>
<p>考虑以上事实，我想说的关于缓存”开销巨大“操作的一条准则就是：除非你真的要搞类似大数阶乘，疯狂递归，大素数分解这样的操作，否则就在纯 javascript 操作中把 <code>useMemo</code> 删掉吧。重渲染元素才是你的瓶颈。请只在渲染树的重要部分使用 <code>useMemo</code>。</p>
<p>问题又来了，<strong>那为啥一定要删掉它们呢</strong>？把所有东西缓存起来不是更好吗？哪怕只让重渲染速度提升了 2ms，这里提升 2ms，那里提升 2ms，累加起来就很可观了呀。换个角度看，如果完全不写 <code>useMemo</code>，那么应用就会在这里慢 2ms，在那里又慢 2ms，很快我们的应用就会比它们原本能达到的程度慢的多了。</p>
<p>听起来很有道理 ，并且，如果不是考虑到另一点的话，以上推论确实 100% 说得通。这一点便是：缓存并不是毫无开销的。如果我们使用 <code>useMemo</code>，在初始渲染过程中 React 就需要缓存其值了——这当然也产生耗时。没错，这耗时很微小，在我们的应用中，缓存上述提到过的排序国家列表耗时不超过 1ms。但是！<strong>这才会产生货真价实的叠加效应</strong>！在初始渲染让你的应用第一次呈现在屏幕前的过程中，当前页面的<strong>每一个</strong>元素都会经历这一过程，这将导致 10~20 ms，或更糟糕的，接近 100ms 的不必要的延时。</p>
<p>与初始渲染相比，重渲染仅仅在页面某些部分改变时发生。在一个架构合理的应用中，只有这些特定区域的组件才会重渲染，而非整个应用（页面）。那么在一次寻常的重渲染中，总的“计算”的消耗和我们上面提到的例子（译者注：指 250 个元素的排序列表）相比，会高出多少呢？2~3 倍？，就假设有 5 倍好了，那也仅仅是节省了 10ms 的渲染时间，这么短的时间间隔我们的肉眼是无法察觉的，并且在十倍的渲染时间下，这 10 ms 也确实很不起眼。可作为代价的是，它确实拖慢了每次都会发生的初始渲染过程😔。</p>
<p>（译者总结：参与初始渲染的是整个页面相关的组件，参与重渲染的只是局部的组件，两者不是一个数量级。参与初始渲染的大量组件，被 <code>useMemo</code> 和 <code>useCallbak</code> 拖慢所产生的叠加明显，远远比参与重渲染的少量组件，被 <code>useMemo</code> 和 <code>useCallbak</code>所优化所产生的叠加效应来的明显！也就是说，资不抵债，这笔优化划不来。）</p>
<h2 id="今天说得够多的了"><a href="#今天说得够多的了" class="headerlink" title="今天说得够多的了"></a>今天说得够多的了</h2><p>上面确实传达了不少信息，希望你能觉得有用，并立马热情澎湃地回过头来 review 你的代码，从 <code>useMemo</code> 和 <code>useCallback</code> 的束缚中解脱出来。下面是一些简短的总结：</p>
<ul>
<li><code>useCallback</code> 和 <code>useMemo</code> 仅仅在后续渲染（也就是重渲染）中起作用，在初始渲染中它们反而是有害的</li>
<li><code>useCallback</code> 和 <code>useMemo</code> 作用于 <code>props</code> 并不能避免组件重渲染。只有当每一个 <code>prop</code> 都被缓存，且组件本身也被缓存的情况下，重渲染才能被避免。只要有一丁点疏忽，那么你做的一切努力就打水漂了。所以说，简单点，把它们都删了吧。</li>
<li>把包裹了“纯 js 操作“的 <code>useMemo</code> 也都删了吧。与组件本身的渲染相比，它缓存数据带来的耗时减少是微不足道的，并且会在初始渲染时消耗额外的内存，造成可以被观察到的延迟。</li>
</ul>
<p>最后的小提示：考虑到 <code>useMemo</code> 和 <code>useCallbak</code> 是如此复杂且脆弱，你应该把它们作为你性能优化计划中最后才考虑的一点。试试其他优化技巧吧，看一下我的其它文章，它们提到了这些技巧（译者注：若文章点赞过百，考虑再翻译一篇）</p>
<ul>
<li><a href="https://link.juejin.cn/?target=https://www.developerway.com/posts/how-to-write-performant-react-code">How to write performant React code: rules, patterns, do’s and don’ts</a></li>
<li><a href="https://link.juejin.cn/?target=https://www.developerway.com/posts/why-custom-react-hooks-could-destroy-your-app-performance">Why custom react hooks could destroy your app performance</a></li>
<li><a href="https://link.juejin.cn/?target=https://www.developerway.com/posts/how-to-write-performant-react-apps-with-context">How to write performant React apps with Context</a></li>
<li><a href="https://link.juejin.cn/?target=https://www.developerway.com/posts/react-key-attribute">React key attribute: best practices for performant lists</a></li>
<li><a href="https://link.juejin.cn/?target=https://www.developerway.com/posts/components-composition-how-to-get-it-right">React components composition: how to get it right</a>.</li>
</ul>
<p>当然，不言而喻的是，测量优先！（没有数据就没有发言权）</p>
<p>希望今天是你在 <code>useMemo</code> 和 <code>useCallbak</code> 地狱中苦苦挣扎的最后一天！✌🏼</p>
<p>作者：佛系社长<br>链接：<a target="_blank" rel="noopener" href="https://juejin.cn/post/7251802404877893689">https://juejin.cn/post/7251802404877893689</a><br>来源：稀土掘金<br>著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/ycs/about" rel="external nofollow noreferrer">掘金-佛系社长</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://gitee.com/chunsuo/ycs.git/ycs/2023/07/18/usecallback%E5%92%8CuseMemo/">https://gitee.com/chunsuo/ycs.git/ycs/2023/07/18/usecallback%E5%92%8CuseMemo/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/ycs/about" target="_blank">掘金-佛系社长</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/ycs/tags/javascript/">
                                    <span class="chip bg-color">javascript</span>
                                </a>
                            
                                <a href="/ycs/tags/React/">
                                    <span class="chip bg-color">React</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/ycs/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/ycs/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/ycs/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/ycs/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    
    <div class="livere-card card" data-aos="fade-up">
    <!-- 来必力City版安装代码 -->
    <div id="lv-container" class="card-content" data-id="city" data-uid="MTAyMC81NzU0Ny8zNDAxMQ==">
        <script type="text/javascript">
            (function (d, s) {
                let j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') {
                    return;
                }

                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活JavaScript。</noscript>
    </div>
    <!-- City版安装代码已完成 -->
</div>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/ycs/2023/08/15/react-Hooks%E4%B9%8B%E5%BC%BA%E5%88%B6%E5%88%B7%E6%96%B0/">
                    <div class="card-image">
                        
                        <img src="https://cn.bing.com/th?id=OHR.MidAutumn2022_ZH-CN9825550508_1920x1200.jpg&rf=LaDigue_1920x1200.jpg" class="responsive-img" alt="React Hooks之forceUpdate">
                        
                        <span class="card-title">React Hooks之forceUpdate</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            日常收集
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2023-08-15
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/ycs/categories/React/" class="post-category">
                                    React
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/ycs/tags/javascript/">
                        <span class="chip bg-color">javascript</span>
                    </a>
                    
                    <a href="/ycs/tags/React/">
                        <span class="chip bg-color">React</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/ycs/2023/06/23/%E8%AE%A9%E4%BA%BA%E6%81%B6%E5%BF%83%E7%9A%84uniapp%E8%BE%93%E5%85%A5%E6%A1%86/">
                    <div class="card-image">
                        
                        <img src="https://img.peapix.com/1995197081526869313_480.jpg" class="responsive-img" alt="让人恶心的uniapp输入框">
                        
                        <span class="card-title">让人恶心的uniapp输入框</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            超级坑
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2023-06-23
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/ycs/categories/uniapp/" class="post-category">
                                    uniapp
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/ycs/tags/uniapp/">
                        <span class="chip bg-color">uniapp</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/ycs/libs/codeBlock/codeBlockFuction.js"></script>


  <!-- 是否加载使用自带的 prismjs. -->
  <script type="text/javascript" src="/ycs/libs/prism/prism.min.js"></script>


<!-- 代码语言 -->

<script type="text/javascript" src="/ycs/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/ycs/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/ycs/libs/codeBlock/codeShrink.js"></script>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/ycs/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2022-2023</span>
            
            <a href="/ycs/about" target="_blank">叶春锁</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">49.1k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://gitee.com/chunsuo" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yechunsuo@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=3196682804" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 3196682804" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/ycs/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/ycs/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 白天和黑夜主题 -->
<div class="stars-con">
    <div id="stars"></div>
    <div id="stars2"></div>
    <div id="stars3"></div>  
</div>

<script>
    function switchNightMode() {
        $('<div class="Cuteen_DarkSky"><div class="Cuteen_DarkPlanet"></div></div>').appendTo($('body')),
        setTimeout(function () {
            $('body').hasClass('DarkMode') 
            ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
            : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
            
            setTimeout(function () {
            $('.Cuteen_DarkSky').fadeOut(1e3, function () {
                $(this).remove()
            })
            }, 2e3)
        })
    }
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/ycs/libs/materialize/materialize.min.js"></script>
    <script src="/ycs/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/ycs/libs/aos/aos.js"></script>
    <script src="/ycs/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/ycs/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/ycs/js/matery.js"></script>

    

    

    <!-- 雪花特效 -->
     
        <script type="text/javascript">
            // 只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/ycs/libs/others/snow.js"><\/script>');
            }
        </script>
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/ycs/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/ycs/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/ycs/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/ycs/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
